using System;
using DNT.RavenQA.Core.Extensions;
using DNT.RavenQA.Core.Models;
using Raven.Client;

namespace DNT.RavenQA.Web.Infrastructure.Commands
{
    public class AcceptAnswerCommand : RavenCommand<AcceptAnswerCommand.Input, VoidResult>
    {
        public struct Input
        {
            public Int32 AnswerId;
            public User User;
        }

        public AcceptAnswerCommand(Input parameter)
            : base(parameter) { }

        public override VoidResult Execute(IDocumentSession session)
        {
            session.EnsureIsNotNull("session");

            var answer = session.Include<Answer>(a => a.QuestionId)
                .Load<Answer>(Parameter.AnswerId);

            if (answer.IsNull())
                throw new NonExistingContributeException(String.Format("Cannot find an answer with id '{0}'.", Parameter.AnswerId));

            var question = session.Load<Question>(answer.QuestionId);

            if (question.IsNull())
                throw new NonExistingContributeException(String.Format("Cannot find a question with id '{0}'.", answer.QuestionId));

            question.SetAsAnswered(answer, Parameter.User);
            return VoidResult.Instance;
        }
    }
}